/**
 * index
 * 2019/9/1
 */

const fs = require('fs-extra');
const path = require('path');

function resolve() {
  return path.resolve(...arguments);
}

module.exports = function () {

  let outputRoot = '', // 输出根路径
    outputPath = '', // 输出目录
    outputStaticPath = '',  // 输出静态资源目录
    srcPath = resolve(__dirname); // 工程目录


  /**
   * 如果有额外的css， 则复制到dist/static/下
   * @param filePath css路径
   * @returns {string} css的文件名
   */
  function dealOtherCss(filePath) {
    let cssFileName = '',
      realPath = '';

    if (filePath && fs.pathExistsSync(realPath = resolve(filePath))) {
      console.log('***', realPath, outputStaticPath);
      cssFileName = path.basename(realPath, '.css');
      fs.copySync(realPath, path.join(outputStaticPath, cssFileName + '.css'));
    }

    return cssFileName;
  }

  /**
   * 生成模板字符串
   * @param {string} mdPath markdown文件名称
   * @param {string} theme 皮肤
   * @param {string} otherCss 其他样式文件
   * @returns {string} HTML文件字符串
   */
  function getHtmlTemp(mdPath, theme, otherCss) {
    let mdStr = '',
      templateFilePath = resolve(srcPath, 'template.html'),
      mdSrcPath = resolve(outputRoot, mdPath),
      htmlStr = fs.readFileSync(templateFilePath, 'utf-8');

    // 获取md文件
    if (!fs.pathExistsSync(mdSrcPath)) {
      throw 'file: ' + mdPath + ' is not exist';
      return false;
    } else {
      mdStr = fs.readFileSync(mdSrcPath, 'utf-8');
    }

    return htmlStr.replace(/{{(\w+)}}/g, function (str, key) {
      if (key === 'css') {
        return `${theme}.css`;
      }

      if (key === 'otherCss') {
        return otherCss && `<link rel="stylesheet" href="./static/${otherCss}.css">` || '';
      }

      if (key === 'mdContent') {
        return mdStr;
      }
    });

  }

  return function (mdFile = 'README.md', outFile = 'index.html', {
    output = 'dist',  // 自定义输出目录名称
    theme = 'default',  // 主题
    css // 其他的css文件
  } = options) {
    let templateStr = '',
      otherCssName = '';

    outputRoot = resolve();
    outputPath = resolve(outputRoot, output);
    outputStaticPath = resolve(outputPath, 'static');

    fs.ensureDirSync(outputStaticPath);

    fs.copySync(resolve(srcPath, 'static'), outputStaticPath); // copy static

    otherCssName = dealOtherCss(css);

    templateStr = getHtmlTemp(mdFile, theme, otherCssName); // get ppt

    // output ppt
    fs.outputFileSync(resolve(outputPath, outFile), templateStr);
    console.log(`read ${mdFile}, output ${outFile} ...`);
  }
};
